var express = require('express');
var router = express.Router();
const fs = require('fs')

// var jwt = require("jsonwebtoken");
/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });

router.get('/regist',function(req,res,next){
    res.render('regist')
})

router.get('/login',function(req,res,next){
  res.render('login')
})
//接口
router.post('/regist',(req,res)=>{
  let user = req.body;
  console.log(user);
  let users = fs.readFileSync("./db/users.json");//所有用户数据
  users = JSON.parse(users)
  // 判断是否重复用户名
  for(let i =0; i<users.length;i++){
    if(users[i].username === user.username){
      res.json({code:0,msg:'重复用户名,重新注册'})
      return
    }
  }
  // 编辑用户ID
  if(users.length==0){
    user.id = 1;
  }else{
    user.id = users[users.length-1].id+1;
  }
  users.push(user);
  console.log(users);
  //存文件
  fs.writeFile('./db/users.json',
  JSON.stringify(users),(err)=>{
    console.log(err);
    if(err) return;
    res.json({code:1,mag:'注册成功'})
  })
})

//登录接口

router.post("/login",(req,res)=>{
  let user = req.body;
  let users = fs.readFileSync("./db/users.json");
  users = JSON.parse(users);
  let u = users.find(u=>u.username === user.username)
  //返回的查找值为 undefined 没有这个用户
  //正常返回一个对象
  if(u===undefined){
    res.json({code:0,msg:'用户名错误'});
  }else{
    if(u.password === user.password){
      res.send({code:1,token});
      res.json({code:1,mag:'登录成功'})

      }else{
        res.json({code:0,msg:"用户名和密码错误"})
      }
  }
  })



module.exports = router;
